package com.example.user.customviewdemo.drawing.shader;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by user on 2016/5/11.
 */
public class OtherShaderView extends View {
    private Paint paint;
    private final float RADIUS = 250;
    private float a = 1;
    private LinearGradient linearGradient;
    private SweepGradient sweepGradient;
    private RadialGradient radialGradient;
    private float x = 500;
    private float y = RADIUS;

    public OtherShaderView(Context context) {
        super(context);
    }

    public OtherShaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        startAnima();
    }

    public OtherShaderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        paint.setShader(new LinearGradient(x,0,x,2*RADIUS, Color.GREEN,Color.WHITE, Shader.TileMode.REPEAT));
        canvas.drawCircle(x,y,RADIUS,paint);

        canvas.translate(0,2*RADIUS + 10);
        paint.setShader(new SweepGradient(x,y,Color.GREEN,Color.WHITE));
        canvas.drawCircle(x,y,RADIUS,paint);

        canvas.translate(0, 2*RADIUS + 10);
        paint.setShader(new RadialGradient(x,y,RADIUS,new int[]{Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW},new float[]{0.2f*a,0.4f*a,0.6f*a,0.8f*a}, Shader.TileMode.REPEAT));
        canvas.drawCircle(x,y,RADIUS,paint);
    }

    private void startAnima(){
        ValueAnimator animator = ValueAnimator.ofFloat(1,1.25f);
        animator.setDuration(2000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                a = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        animator.start();
    }
}
